package com.msb.简单树;

import java.util.HashMap;
import java.util.Map;

/**
 * @author whf
 * @date 2024-12-18 18:07
 * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 */
public class _根据先序和中序数组求二叉树_hard {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) {
            return null;
        } else if (preorder.length != inorder.length) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return buildTree(preorder, 0, preorder.length - 1, 0, map);
    }

    public TreeNode buildTree(int[] preorder, int L1, int R1, int L2, Map<Integer, Integer> map) {
        if (L1 > R1) {
            return null;
        }
        TreeNode res = new TreeNode(preorder[L1]);
        if (L1 == R1) {
            return res;
        }
        int find = map.get(preorder[L1]);
        res.left = buildTree(preorder, L1 + 1, L1 + find - L2, L2, map);
        res.right = buildTree(preorder, L1 + find - L2 + 1, R1, find + 1, map);
        return res;
    }
}
